<template>
  <div class="sdy-cart">
    <SdyHeader title="啥都有" back></SdyHeader>
    <div class="top">
      <van-checkbox v-model="toggleAll" checked-color="#ee0a24">全选</van-checkbox>
      <!-- <van-radio :checked="selectAll" class="select-item" name="1"></van-radio> -->
    </div>
    <ul>
      <li v-for="item in CartInfo" :key="item.proid">
        <van-checkbox v-model="item.flag" @click="updateStatus(item.cartid, item.flag)"
          checked-color="#ee0a24"></van-checkbox>
        <!-- <van-radio  @click="updateStatus(item.cartid,!item.flag)" :checked="item.flag" class="select-item" name="1"></van-radio> -->
        <van-card class="goods1-item" :price="item.originprice" desc="描述信息" :title="item.proname" :thumb="item.img1">
          <template #tags>
            <van-tag plain type="primary">-</van-tag>
            <input class="num-inp" type="text" :value="item.num">
            <van-tag plain type="primary">+</van-tag>
          </template>
          <template #footer>
            <van-button size="mini">按钮</van-button>
            <van-button @click="removeCart(item.cartid)" size="mini">删除</van-button>
          </template>
        </van-card>
      </li>
    </ul>
    <div class="bottom">
      总价：{{ totalPrice }}
      <van-button type="danger" @click="clearCart">清空购物车</van-button>
    </div>
  </div>
  <hr style="height:5px;background-color: red;">
  <!-- 热门搜索 -->
  <div class="goods">
    <div class="goods-item" v-for="item in goodsList" :key="item.proid">
      <img :src="item.img1" alt="">
      <p class="title van-multi-ellipsis--l2">
        {{ item.proname }}
      </p>
      <p class="price">
        <span class="current">
          ￥ {{ item.issale ? (item.originprice * 10 / item.discount).toFixed(2) : item.originprice.toFixed(2) }}
        </span>
        <span class="old">
          ￥ {{ item.originprice.toFixed(2) }}
        </span>
      </p>
      <p class="tags">
        <van-tag type="danger">{{ item.category }}</van-tag>
        <van-tag type="primary">{{ item.brand }}</van-tag>
      </p>
    </div>
  </div>
  <Teleport to="#sdy-footer">
    <van-action-bar>
      <van-action-bar-icon icon="chat-o" text="客服" />
      <van-action-bar-icon @click="$router.push('/order')" icon="cart-o" text="查看订单" />
      <van-action-bar-icon icon="shop-o" text="店铺" />
      <van-action-bar-button @click="addOrderHandler" type="danger" text="生成订单" />
    </van-action-bar>
  </Teleport>


</template>

<script setup lang="ts">
import { ref, onMounted, computed, reactive } from 'vue'
import { useRouter, type Router } from 'vue-router'
import { Dialog } from 'vant';
//  import  { showDialog } from 'vant';
import { cartListApi, updateStatusApi, updateAllStatusApi, removeCartApi, clearAllCartApi } from '@/api/Cart'
import { goodListApi } from '@/api/goods'
import { addOrderApi } from '@/api/order'
import type { MyHotItem, MyCartItem } from '@/config/interface'


const userid = window.localStorage.getItem('userid')
const token = window.localStorage.getItem('token')

const $router: Router = useRouter()
// 验证token  userid
const testToken = () => {
  if (!userid || !token) {
    Dialog({
      title: '提示',
      message: '您还没有登录，请登录',
    }).then(() => {
      //拿来回哪去
      $router.push('/login')
    });
    return
  }
}

// 准备一个数组来接收数据，渲染页面
const CartInfo = ref<MyCartItem[]>([])
// 获取购物车列表
const goodsCartList = async () => {
  const res = await cartListApi(userid as string)
  CartInfo.value = res.data
  console.log(res);
}
// 获取热门相关内容
const goodInfo = reactive({ count: 1, limitNum: 10 })
const goodsList = ref<MyHotItem[]>([])
const getGoodsList = () => {
  setInterval(async () => {
    const res = await goodListApi(goodInfo)
    goodsList.value = [...goodsList.value, ...res.data]
    goodInfo.count++
    // console.log(goodInfo);
    // console.log( goodsList.value);
  }, Math.random() * 2000)

}

// 准备一个全选按钮
// const selectAll = computed(() => {
//   return CartInfo.value.every(item => item.flag)
// })

const toggleAll = computed({
  get() {
    return CartInfo.value.every(item => item.flag)
  },
  set(val) {
    updateAllStatus(val)
    console.log(val);
  }
})
// 修改所有选中状态
const updateAllStatus = async (val: boolean) => {
  const res = await updateAllStatusApi(userid as string, val)
  console.log(res);
  if (((res as unknown) as { code: string }).code === '200') {
    goodsCartList()
  }
}

// 准备一个总价
const totalPrice = computed(() => {
  return CartInfo.value.reduce((prev, item) => {
    if (item.flag) {
      return prev + (item.originprice * item.num)
    } else {
      return prev
    }
  }, 0)
})

// 修改每一条选中状态
const updateStatus = async (id: string, flag: boolean) => {
  const res = await updateStatusApi(id, flag)
  // console.log(res);
  if (((res as unknown) as { code: string }).code === '200') {
    goodsCartList()

  }
}
// 删除每一件商品
const removeCart = (cartid: string) => {
  Dialog.confirm({
    title: '移除购物车',
    message:
      '如果移除请确认，否则取消',
  })
    .then(async () => {
      // on confirm\
      const res = await removeCartApi(cartid)
      console.log(res);
      if (((res as unknown) as { code: string }).code === '200') {
        goodsCartList()
      }
    })
}

// 清空购物车
const clearCart = () => {
  Dialog.confirm({
    title: '清空购物车',
    message:
      '如果清空请确认，否则取消',
  }).then(async () => {
    const res = await clearAllCartApi(userid as string)
    console.log(res);
    if (((res as unknown) as { code: string }).code === '200') {
      CartInfo.value = ([])
    }
  })
}

onMounted(() => {
  testToken()
  goodsCartList()
  getGoodsList()
})


// 添加一个订单
const addOrderHandler = async () => {
  const res = await addOrderApi(userid as string)
  console.log(res);

  // 把订单储存在location里面
  window.localStorage.setItem('time', ((res as unknown) as { time: string }).time)

}

</script>

<style scoped lang="scss">
@import '@/styles/variable.scss';

.sdy-cart {
  >.bottom {
    display: flex;
    justify-content: space-between;
    padding: 5px;
  }

  li {
    display: flex;
    box-sizing: border-box;
    padding: 0 10px;

    >.select-item {
      width: 30px;
    }

    >.goods1-item {
      flex: 1;
    }
  }

}

.goods {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-evenly;

  >.goods-item {
    width: 45%;
    border: 1px solid #333;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 5px;
    overflow: hidden;
    padding-bottom: 5px;

    >p {
      margin: 0;
    }

    >img {
      width: 100%;
      height: 170px;
      display: block;
    }

    >.title {
      font-size: 12px;
    }

    >.price {
      font-size: 12px;
      color: #ccc;
      width: 100%;
      display: flex;
      justify-content: space-evenly;

      >.current {
        font-size: 16px;
        color: $globalColor;
      }

      >.old {
        text-decoration: line-through;
      }
    }

    >.tags {
      width: 100%;
      display: flex;
      justify-content: space-evenly;
    }
  }
}

.num-inp {
  width: 30px;
  text-align: center;
  margin: 0 10px;

}
</style>